package cn.com.jslh.boarpro.util;

import android.app.ProgressDialog;
import android.content.Context;
import android.util.Log;
import android.widget.Toast;

import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.callback.Callback;
import com.lzy.okgo.model.HttpHeaders;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Progress;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import cn.com.jslh.boarpro.base.BaseApplication;


/**
 * 作者：周洲 on 2017/3/22 15:07
 * <p>
 * 邮箱：double0zhou@126.com
 */

public class NetBean {
    private CacheMode cacheMode;
    private String             url;
    private String             method;
    private HttpParams requestParams;
    private NetSuccessListener netSuccessListener;
    private NetFaildListener   netFaildListener;
    private ProgressDialog     progressDialog;
    private Context            context;
    private boolean showDialog = true;
    private String json;

    private NetBean(Builder builder) {
        this(builder, "post");
    }

    private NetBean(Builder builder, String way) {
        this.url = builder.url;
        this.method = builder.method;
        this.requestParams = builder.requestParams;
        this.netSuccessListener = builder.netSuccessListener;
        this.netFaildListener = builder.netFaildListener;
        this.context = builder.context;
        this.showDialog = builder.showDialog;
        this.cacheMode = builder.cacheMode;
        this.json=builder.json;
        if ("post".equalsIgnoreCase(way)) {
            OkGo.<String>post(url + method)
                    .params(requestParams)
                    .upJson(json)
                    .cacheMode(cacheMode)
                    .tag(method)
                    .execute(new Callback<String>() {
                        @Override
                        public void onStart(Request<String, ? extends Request> request) {
                            if (showDialog) {
                                showDialog("loading...");
                            }
                        }

                        @Override
                        public void onSuccess(Response<String> response) {
                            try {
                                JSONObject resJson = new JSONObject(response.getRawResponse().body().string().trim());
                               if(resJson!=null){
                                   netSuccessListener.Success(resJson);
                               }else {
                                   String msg = resJson.getString("message");
                                   if (netFaildListener != null) {
                                       netFaildListener.Faild(msg);
                                   }
                               }



//                                if ((resJson.getInt("code") == 200)) {
//                                    if (resJson.has("data") && resJson.get("data") != null) {
//                                        if (netSuccessListener != null) {
//                                            netSuccessListener.Success(resJson.get("data"));
//                                        }
//                                    } else {
//                                        netSuccessListener.Success(new JSONObject());
//                                    }
//                                }else
//                                if(res!=null){
//                                    netSuccessListener.Success(res);
//                                }else {
//                                    String msg = resJson.getString("message");
//                                    if (netFaildListener != null) {
//                                        netFaildListener.Faild(msg);
//                                    }
//                                }
                            } catch (JSONException e) {
                                //                    e.printStackTrace();
                                if (netFaildListener != null) {
                                    netFaildListener.Faild(e.getMessage());
                                }
                            } catch (IOException e) {
                                if (netFaildListener != null) {
                                    netFaildListener.Faild(e.getMessage());
                                }
                            }
                        }

                        @Override
                        public void onCacheSuccess(Response<String> response) {

                        }

                        @Override
                        public void onError(Response<String> response) {
                            if (netFaildListener != null) {
                                netFaildListener.Faild(response.message());
                            } else {
                                Toast.makeText(context, response.message(), Toast.LENGTH_SHORT).show();
                            }
                        }

                        @Override
                        public void onFinish() {
                            if (showDialog) {
                                cancleDialog();
                            }
                        }

                        @Override
                        public void uploadProgress(Progress progress) {

                        }

                        @Override
                        public void downloadProgress(Progress progress) {

                        }

                        @Override
                        public String convertResponse(okhttp3.Response response) throws Throwable {
                            return null;
                        }
                    });
        } else {
            OkGo.<String>get(url + method)
                    .params(requestParams)
                    .cacheMode(cacheMode)
                    .tag(method)
                    .execute(new Callback<String>() {
                        @Override
                        public void onStart(Request<String, ? extends Request> request) {
                            if (showDialog) {
                                showDialog("loading...");
                            }
                        }

                        @Override
                        public void onSuccess(Response<String> response) {
                            try {
                                JSONObject resJson = new JSONObject(response.getRawResponse().body().string().trim());
                                if ((resJson.getInt("code") == 200)) {
                                    if (resJson.has("data") && resJson.get("data") != null) {
                                        if (netSuccessListener != null) {
                                            netSuccessListener.Success(resJson.get("data"));
                                        }
                                    } else {
                                        netSuccessListener.Success(new JSONObject());
                                    }
                                } else {
                                    String msg = resJson.getString("message");
                                    if (netFaildListener != null) {
                                        netFaildListener.Faild(msg);
                                    }
                                }
                            } catch (JSONException e) {
                                //                    e.printStackTrace();
                                if (netFaildListener != null) {
                                    netFaildListener.Faild(e.getMessage());
                                }
                            } catch (IOException e) {
                                if (netFaildListener != null) {
                                    netFaildListener.Faild(e.getMessage());
                                }
                            }
                        }

                        @Override
                        public void onCacheSuccess(Response<String> response) {

                        }

                        @Override
                        public void onError(Response<String> response) {
                            if (netFaildListener != null) {
                                netFaildListener.Faild(response.message());
                            } else {
                                Toast.makeText(context, response.message(), Toast.LENGTH_SHORT).show();
                            }
                        }

                        @Override
                        public void onFinish() {
                            if (showDialog) {
                                cancleDialog();
                            }
                        }

                        @Override
                        public void uploadProgress(Progress progress) {

                        }

                        @Override
                        public void downloadProgress(Progress progress) {

                        }

                        @Override
                        public String convertResponse(okhttp3.Response response) throws Throwable {
                            return null;
                        }
                    });
        }

    }


    public void showDialog(String msg) {
        if (progressDialog == null) {
            progressDialog = new ProgressDialog(context, ProgressDialog.STYLE_SPINNER);
        }
        progressDialog.setCancelable(false);
        progressDialog.setMessage(msg);
        progressDialog.show();
    }

    public void cancleDialog() {
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.cancel();
            progressDialog = null;
        }
    }

    public abstract static class NetSuccessListener {
        public abstract void Success(JSONArray jsonArray) throws JSONException;

        public void Success(JSONObject resJson) throws JSONException {

        }

        public void Success(Object o) throws JSONException {

        }

        public void Success(String str){

        }

    }

    public interface NetFaildListener {
        void Faild(String str);
    }

    public static class Builder {
        private CacheMode cacheMode;
        private String             url;
        private String             method;
        private HttpParams requestParams;
        private NetSuccessListener netSuccessListener;
        private NetFaildListener   netFaildListener;
        private Context            context;
        private boolean showDialog = true;
        private HttpHeaders headers    = new HttpHeaders();
        private String json ;

        public Builder(Context context) {
            this.context = context;
            requestParams = new HttpParams();
            this.url = BaseApplication.upAppUrl;
            requestParams.put("userId", SPUtils.getInstance().getString(BaseApplication.FUSERID));
            requestParams.put("time", TimeUtils.getNowString());
            requestParams.put("phonetype", android.os.Build.MODEL);
            requestParams.put("appVersionId", AppUtils.getAppVersionCode());
            cacheMode = CacheMode.FIRST_CACHE_THEN_REQUEST;
        }


        public Builder setCacheMode(CacheMode cacheMode) {
            this.cacheMode = cacheMode;
            return this;
        }

        public Builder setBaseUrl(String url) {
            this.url = url;
            return this;
        }

        public Builder addParams(String key, String value) {
            requestParams.put(key, value);
            return this;
        }



        public Builder isShowDialog(boolean show) {
            this.showDialog = show;
            return this;
        }

        public Builder setMethod(String method) {
            this.method = method;
            return this;
        }

        public Builder  setJson(String json){
            this.json=json;
            return this;
        }

        public Builder setSuccess(NetSuccessListener netSuccessListener) {
            this.netSuccessListener = netSuccessListener;
            return this;
        }

        public Builder setFaild(NetFaildListener netFaildListener) {
            this.netFaildListener = netFaildListener;
            return this;
        }

        public NetBean build(String way) {

            return new NetBean(this, way);
        }

        public NetBean build() {
            return new NetBean(this);
        }

        public Builder setHeader(String key, String value) {
            headers.put(key, value);
            return this;
        }
    }
}
